<!DOCTYPE html>
<html class="x-admin-sm">

<head>
    <meta charset="UTF-8">
    <title>学生列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script src="__ADMIN__/lib/layui/layui.js" charset="utf-8"></script>
    <link rel="stylesheet" href="__ADMIN__/css/font.css">
    <link rel="stylesheet" href="__ADMIN__/css/xadmin.css">
    <script type="text/javascript" src="__ADMIN__/js/xadmin.js"></script>
    <!--[if lt IE 9]>
    <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
    <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
<table id="test" lay-filter="test" lay-data="{id: 'test'}"></table>


<!--//头部工具栏-->
<script type="text/html" id="toolbarDemo">
    <div>

        <div class="demoTable">
            <div class="layui-form">
                搜索类型
                <div class="layui-input-inline">
                    <select id="check" name="check" class="layui-select" lay-verify="required"
                            lay-filter="selectTemplate" lay-search width="80px">
                        <option value=""></option>
                        <option value="1">ID</option>
                        <option value="2">姓名</option>
                    </select>
                </div>
                搜索内容：
                <div class="layui-inline">
                    <input class="layui-input" name="value" id="inputval" autocomplete="off" required>
                </div>
                <button type="button" class="layui-btn" data-type="reload">搜索</button>
            </div>

        </div>
    </div>

    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" lay-event="addData">新增 <span
                class="glyphicon glyphicon-plus"></span></button>
        <button class="layui-btn layui-btn-sm" lay-event="refresh">刷新表格</button>
        <!--        <button class="layui-btn layui-btn-sm" data-type="reload" lay-event="search">查询</button>-->
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="dels">删除选中行</button>

        <div style="display: inline-flex;position: relative;">
            <button class="layui-btn layui-bg-cyan" id='uploadExcel'>一键导入</button>
            <form id="uploadForm" enctype="multipart/form-data">
                <input style="opacity:0;width:113px;height:38px;position:absolute;right:0;top:0;" id="files" type="file"
                       name="excel"
                       accept=".csv, .xls, .xlsx"/>
            </form>
        </div>
    </div>
</script>

<!--    编辑弹出层-->
<div id="edit_form" style="display:none">
    <div class="layui-form">
        <div class="text" style="width: 1000px;height: 100%;margin: auto;padding-top: 20px;">
            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>ID</label>
                <div class="layui-input-inline">
                    <input type="text" id="id" name="id" required lay-verify="required|number|idcheck"
                           autocomplete="off"
                           class="layui-input"></div>
                <div class="layui-form-mid layui-word-aux">
                    <span class="x-red">*</span>将会成为用户唯一标识
                </div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>姓名</label>
                <div class="layui-input-inline">
                    <input type="text" id="name" name="name" required lay-verify="required|expertname"
                           autocomplete="off"
                           class="layui-input"></div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>密码</label>
                <div class="layui-input-inline">
                    <input type="text" id="pwd" name="pwd" required lay-verify="required|pass" autocomplete="off"
                           class="layui-input"></div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>性别</label>
                <div class="layui-input-inline">
                    <select id="sex" name="sex" lay-verify="required" autocomplete="off" class="layui-input">
                        <option value=""></option>
                        {volist name="sexlist" id="vo"}
                        <option value="{$vo.sex}">{$vo.sex}</option>
                        {/volist}
                    </select>
                </div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>邮箱</label>
                <div class="layui-input-inline">
                    <input type="text" id="email" name="email" required lay-verify="email" autocomplete="off"
                           class="layui-input"></div>
                <div class="layui-form-mid layui-word-aux">
                </div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>年龄</label>
                <div class="layui-input-inline">
                    <input type="text" id="age" name="age" required lay-verify="required|agecheck" autocomplete="off"
                           class="layui-input"></div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>学院</label>
                <div class="layui-input-inline">
                    <select id="depart" name="depart" lay-verify="required" autocomplete="off" class="layui-input">
                        <option value=""></option>
                        {volist name="departlist" id="vo"}
                        <option value="{$vo.depart}">{$vo.depart}</option>
                        {/volist}
                    </select>
                </div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>地址</label>
                <div class="layui-input-inline">
                    <input type="text" id="address" name="address" required lay-verify="required" autocomplete="off"
                           class="layui-input"></div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>手机</label>
                <div class="layui-input-inline">
                    <input type="text" id="phone" name="phone" required lay-verify="required|phone" autocomplete="off"
                           class="layui-input"></div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>民族</label>
                <div class="layui-input-inline">
                    <input type="text" id="nation" name="nation" required="" lay-verify="required"
                           autocomplete="off" class="layui-input"></div>
            </div>

            <div class="layui-form-item" style="width: 45%;float: left;clear: none;margin-bottom: 30px;">
                <label class="layui-form-label"></label>
                <button class="layui-btn" lay-filter="update" lay-submit="update">修改</button>
            </div>
        </div>
    </div>
</div>
</div>

<!--//操作栏-->
<script type="text/html" id="barDemo">
    <a style=" text-decoration: none"><i class="layui-icon layui-icon-edit toolbars" lay-event="edit" title="编辑"></i>
    </a>
    <a style=" text-decoration: none"><i class="layui-icon layui-icon-delete" lay-event="del" title="删除"></i> </a>
</script>
<script>
    var editid;
    var uneditid;
    layui.use(['form', 'layer', 'jquery', 'table'], function () {
        var table = layui.table;
        $ = layui.jquery;
        var form = layui.form,
            layer = layui.layer;
        //自定义验证规则
        form.verify({
            expertname: [/^[\u4e00-\u9fa5]{2,4}$|^[a-zA-Z]{1,30}$/, '姓名只能为2至4个汉字或1至30个英文单词'],
            pass: [/^[a-zA-Z]\w{5,17}$/, '以字母开头，长度在6~18之间，只能包含字母、数字和下划线'],
            agecheck: [/(^[1-2][0-9]$)/, '只能输入10到29之间任意数字'],
        });

        //修改监听
        form.on('submit(update)', function (data) {
            var id = data.field.id;
            var name = data.field.name;
            var pwd = data.field.pwd;
            var sex = data.field.sex;
            var mail = data.field.email;
            var age = data.field.age;
            var depart = data.field.depart;
            var address = data.field.address;
            var phone = data.field.phone;
            var nation = data.field.nation;
            //console.log(data.field);
            editid = id;
            if (editid == uneditid) {
                $.ajax({
                    type: "post",
                    url: "../Admin/studentupdate",
                    dataType: "json",
                    data: {
                        "id": id, "name": name, "pwd": pwd, "sex": sex, "mail": mail, "age": age,
                        "depart": depart, "address": address, "phone": phone, "nation": nation
                    },
                    async: false,//必须是同步提交的
                    success: function (data) {
                        // console.log(data);
                        layer.alert('修改成功', {icon: 6}, function (index) {
                            layer.closeAll();
                            table.reload('searchreload');
                        });
                    },
                });
            } else {
                $.ajax({
                    type: "post",
                    url: "{:url('Admin/studentdel')}",
                    dataType: "json",
                    data: {"id": uneditid},
                    async: false,
                    success: function (data) {
                        $.ajax({
                            url: "../Admin/studentidcheck",
                            type: 'POST',
                            dataType: "json",
                            data: {"id": editid},
                            async: false,//必须是同步提交的
                            success: function (res) {
                                // console.log(res.data);
                                if (res.data == 1) {
                                    layer.msg('ID已存在，请修改ID！', {icon: 5});
                                } else if (res.data == 0) {
                                    $.ajax({
                                        url: "../Admin/studentinsert",
                                        type: "post",
                                        dataType: "json",
                                        data: {
                                            "id": id, "name": name, "pwd": pwd, "sex": sex, "mail": mail, "age": age,
                                            "depart": depart, "address": address, "phone": phone, "nation": nation
                                        },
                                        async: false,//必须是同步提交的
                                        success: function (t) {
                                           // console.log(t);
                                            layer.alert('修改成功', {icon: 6}, function (index) {
                                                layer.closeAll();
                                                table.reload('searchreload');
                                            });
                                        },
                                    });

                                }
                            },
                        });
                    }
                });
            }
        });
    });

    layui.use('table', function () {
        var table = layui.table;
        table.render({
            even: false //开启隔行背景
          //  , size: 'sm' //小尺寸的表格
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , minheight: "800px"
            , elem: '#test'
            , page: true
            , id: 'searchreload'
            , limit: 12
            , height: 650
            , url: "{:url('Admin/studentjson')}"
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "刷新页面试试", //解析提示文本
                    "count": res.total, //解析数据长度
                    "data": res.data//解析数据列表
                };
            },
            cols: [[
                {field: 'id', type: 'checkbox', width: 50, fixed: 'left'}
                , {field: 'id', title: '学号', width: 80, sort: true}
                , {field: 'name', title: '姓名', width: 80}
                , {field: 'pwd', title: '密码', width: 100}
                , {field: 'salt', title: '盐值', width: 100}
                , {field: 'sex', title: '性别', width: 80}
                , {field: 'mail', title: '邮箱', width: 120}
                , {field: 'age', title: '年龄', width: 80, sort: true}
                , {field: 'nation', title: '民族', width: 100}
                , {field: 'address', title: '地址', width: 150}
                , {field: 'phone', title: '手机', width: 120}
                , {field: 'depart', title: '学院', width: 150}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 120}
            ]],
            done: function (res) {
                uploadfile();
            }

        });

        //查询表格重载  两种的查询方式
        $('.demoTable .layui-btn').on('click', function () {
         //   console.log(document.getElementById("check").value);
            table.reload('searchreload', {
                where: { //设定异步数据接口的额外参数，任意设
                    type: document.getElementById("check").value,
                    value: $("#inputval").val()
                },
                page: {
                    curr: 1
                }
            });
        });


        //监听头部工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                //新增
                case 'addData':
                    layer.open({
                        type: 2,
                        title: '学生添加',
                        shadeClose: true,
                        shade: false,
                        //btn: ['确定', '取消'],
                        maxmin: true, //开启最大化最小化按钮
                        area: ['1100px', '540px'],
                        content: ['studentadd'],
                        end: function () {
                            table.reload('searchreload');
                        }
                    });
                    break;


                //批量删除
                case 'dels':
                    var data = checkStatus.data;
                    var ids = [];
                    data.forEach(function (item) {
                        ids.push(item.id);
                    });
                    // console.log(ids);
                    if (data.length == '') {
                        layer.msg("未选择数据");
                    } else {
                        layer.confirm('真的删除选中数据吗', function (index) {
                            layer.close(index);
                            $.ajax({
                                type: "post",
                                url: "{:url('Admin/studentdels')}",
                                dataType: "json",
                                data: {"ids": ids},
                                async: false,
                                success: function (data) {
                                  //  console.log(data);
                                    layer.msg("删除成功！");
                                    table.reload('searchreload');
                                }
                            });
                            //提示的应该是这个 建议修改
                            // layer.msg("删除成功");
                            // table.reload('searchreload');
                        })
                    }
                    break;
                case 'refresh':
                    location.reload();
                    //able.reload('searchreload');  正确 搜索存在问题 导致无法刷新
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    layer.close(index);
                    $.ajax({
                        type: "post",
                        url: "{:url('Admin/studentdel')}",
                        dataType: "json",
                        data: {"id": data.id},
                        async: false,
                        success: function (data) {
                            layer.msg("删除成功！");
                            table.reload('searchreload');
                        },
                        error: function (data) {
                            layer.msg("删除失败！");
                            table.reload('searchreload');
                        }

                    });
                });
            } else if (obj.event === 'edit') {
                var id = data.id;
                layui.use('layer', function () {
                    var layer = layui.layer;
                    layer.open({
                        type: 1,
                        title: "学生修改",
                        shade: false,
                        area: ['1100px', '550px'],
                        content: $('#edit_form').html(),
                        success: function (layero, index) {
                            uneditid = id;

                            $.ajax({
                                type: "post",
                                url: "{:url('Admin/geteditstudent')}",
                                dataType: "json",
                                data: {"id": data.id},
                                async: false,
                                success: function (data) {

                                    table.reload('searchreload');

                                    $(" input[name='id']").val(data.list3.id);
                                    $(" input[name='name']").val(data.list3.name);
                                    $(" input[name='pwd']").val(data.list3.pwd);

                                    var selecctsexval;
                                    var selectdepartval;
                                    var selectsex = document.getElementById("sex");
                                    var selectdepart = document.getElementById("depart");
                                    for (var i = 0; i < selectsex.options.length; i++) {
                                        if (selectsex.options[i].value == data.list3.sex) {
                                            selecctsexval = selectsex.options[i].value;
                                            selectsex.options[i].selected = true;
                                            $("input[name='sex']").val(selectsex.options[i].value);
                                        }
                                    }
                                    for (var i = 0; i < selectdepart.options.length; i++) {
                                        if (selectdepart.options[i].value == data.list3.depart) {
                                            selectdepartval = selectdepart.options[i].value;
                                            selectdepart.options[i].selected = true;
                                            $("input[name='depart']").val(selectdepart.options[i].value);
                                        }
                                    }
                                    //下拉框必须先赋值在 选中 再渲染
                                    $(layero).find('select[name=sex]').val(selecctsexval);
                                    $(layero).find('select[name=depart]').val(selectdepartval);
                                    $(" input[name='email']").val(data.list3.mail);
                                    $(" input[name='age']").val(data.list3.age);
                                    $(" input[name='address']").val(data.list3.address);
                                    $(" input[name='phone']").val(data.list3.phone);
                                    $(" input[name='nation']").val(data.list3.nation);
                                }
                            });
                            layui.form.render('select');
                        }
                    });
                })
            }
        })
    });

    //Excel数据导入
    function uploadfile() {
        $("#files").on("change", function (e) {
            var file = document.getElementById("files").files[0];
            var val = document.getElementById("files").value;
            var suffix = val.substr(val.indexOf("."));

            //只能选择Excel类型的文件
            if (suffix == '' || suffix == null) return;
            if (suffix != '.csv' && suffix != '.xlsx' && suffix != '.xls') {
                $('#files').val("");
                layer.msg('只能选择Excel类型的文件', {icon: 0, time: 2000, anim: 6});
                return;
            }

            // layer.load(); //加载框
            var formData = new FormData($('#uploadForm')[0]);
            $.ajax({
                type: 'post',
                url: '{:url("admin/studentexcelimport")}',
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                timeout: 0,
                async: false,
                success: function (res) {
                  //  console.log(res);
                    if (res.data == 0) {
                        layer.msg('导入失败全为重复数据 或 所选文件无数据！');
                    } else {
                        layer.msg('成功导入【' + res.data + '】条数据');
                    }
                }
            })

        })
    }
</script>
</body>
</html>